package cn.getech.data.development.utils.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Component
public class SpringIpAndHostUtil implements ApplicationListener<WebServerInitializedEvent> {

    private static Logger log = LoggerFactory.getLogger(SpringIpAndHostUtil.class);
    private static Integer serverPort = null;


    /// 获取当前服务器地址
    public static String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (Exception e) {
            log.error("获取服务器地址异常！error:{}", e.getMessage());
        }
        return "http://" + address.getHostAddress() + ":" + serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        serverPort = webServerInitializedEvent.getWebServer().getPort();
    }
}
